#include "processdialog.h"
#include <QDateTime>
#include <QUuid>

ProcessDialog::ProcessDialog(QWidget *parent)
    : QDialog(parent)
    , m_isEditMode(false)
{
    setupUI();
    setupConnections();
    loadDepartments();
    generateProcessId();
    setWindowTitle("添加工序");
    resize(400, 350);
}

ProcessDialog::ProcessDialog(const QString &processId, QWidget *parent)
    : QDialog(parent)
    , m_isEditMode(true)
    , m_originalProcessId(processId)
{
    setupUI();
    setupConnections();
    loadDepartments();
    setWindowTitle("编辑工序");
    resize(400, 350);
    
    // 在编辑模式下禁用工序编号编辑
    m_processIdEdit->setReadOnly(true);
    m_generateIdBtn->setEnabled(false);
}

ProcessDialog::~ProcessDialog()
{
}

void ProcessDialog::setupUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 创建表单布局
    QFormLayout *formLayout = new QFormLayout();
    
    // 工序编号行
    QHBoxLayout *idLayout = new QHBoxLayout();
    m_processIdEdit = new QLineEdit();
    m_processIdEdit->setPlaceholderText("请输入工序编号");
    m_processIdEdit->setMaxLength(20);
    
    m_generateIdBtn = new QPushButton("自动生成");
    m_generateIdBtn->setFixedWidth(80);
    
    idLayout->addWidget(m_processIdEdit);
    idLayout->addWidget(m_generateIdBtn);
    
    formLayout->addRow("工序编号:", idLayout);
    
    // 工序名称
    m_nameEdit = new QLineEdit();
    m_nameEdit->setPlaceholderText("请输入工序名称");
    m_nameEdit->setMaxLength(50);
    formLayout->addRow("工序名称:", m_nameEdit);
    
    // 工序描述
    m_descriptionEdit = new QTextEdit();
    m_descriptionEdit->setPlaceholderText("请输入工序描述（可选）");
    m_descriptionEdit->setMaximumHeight(80);
    formLayout->addRow("工序描述:", m_descriptionEdit);
    
    // 计件单价
    m_pieceRateSpinBox = new QDoubleSpinBox();
    m_pieceRateSpinBox->setRange(0.001, 999.999);
    m_pieceRateSpinBox->setDecimals(3);
    m_pieceRateSpinBox->setSuffix(" 元");
    m_pieceRateSpinBox->setValue(0.001);
    formLayout->addRow("计件单价:", m_pieceRateSpinBox);
    
    // 所属班组
    m_departmentCombo = new QComboBox();
    formLayout->addRow("所属班组:", m_departmentCombo);
    
    mainLayout->addLayout(formLayout);
    
    // 按钮区域
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    
    m_okBtn = new QPushButton("确定");
    m_cancelBtn = new QPushButton("取消");
    
    m_okBtn->setDefault(true);
    
    buttonLayout->addWidget(m_okBtn);
    buttonLayout->addWidget(m_cancelBtn);
    
    mainLayout->addLayout(buttonLayout);
    
    // 设置输入验证
    QRegExpValidator *idValidator = new QRegExpValidator(QRegExp("[A-Za-z0-9_-]+"), this);
    m_processIdEdit->setValidator(idValidator);
}

void ProcessDialog::setupConnections()
{
    connect(m_generateIdBtn, &QPushButton::clicked, this, &ProcessDialog::generateProcessId);
    connect(m_processIdEdit, &QLineEdit::textChanged, this, &ProcessDialog::onProcessIdChanged);
    connect(m_okBtn, &QPushButton::clicked, this, &ProcessDialog::accept);
    connect(m_cancelBtn, &QPushButton::clicked, this, &ProcessDialog::reject);
}

void ProcessDialog::loadDepartments()
{
    m_departmentCombo->clear();
    m_departmentMap.clear();
    
    QSqlQuery query("SELECT id, name FROM departments ORDER BY name");
    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        m_departmentCombo->addItem(name);
        m_departmentMap[name] = id;
    }
}

void ProcessDialog::generateProcessId()
{
    // 生成格式为 GX_YYYYMMDD_XXX 的工序编号
    QString date = QDateTime::currentDateTime().toString("yyyyMMdd");
    
    // 查询当天已有的工序数量
    QSqlQuery query;
    query.prepare("SELECT COUNT(*) FROM processes WHERE process_id LIKE ?");
    query.addBindValue(QString("GX_%1_%").arg(date));
    
    int count = 0;
    if (query.exec() && query.next()) {
        count = query.value(0).toInt();
    }
    
    QString processId = QString("GX_%1_%2").arg(date).arg(count + 1, 3, 10, QChar('0'));
    
    // 确保编号唯一
    while (isProcessIdExists(processId)) {
        count++;
        processId = QString("GX_%1_%2").arg(date).arg(count + 1, 3, 10, QChar('0'));
    }
    
    m_processIdEdit->setText(processId);
}

bool ProcessDialog::isProcessIdExists(const QString &processId)
{
    QSqlQuery query;
    query.prepare("SELECT COUNT(*) FROM processes WHERE process_id = ? AND process_id != ?");
    query.addBindValue(processId);
    query.addBindValue(m_originalProcessId); // 编辑模式下排除自己
    
    if (query.exec() && query.next()) {
        return query.value(0).toInt() > 0;
    }
    return false;
}

void ProcessDialog::onProcessIdChanged()
{
    QString processId = m_processIdEdit->text().trimmed();
    if (!processId.isEmpty() && isProcessIdExists(processId)) {
        m_processIdEdit->setStyleSheet("border: 2px solid red;");
        m_okBtn->setEnabled(false);
    } else {
        m_processIdEdit->setStyleSheet("");
        m_okBtn->setEnabled(true);
    }
}

bool ProcessDialog::validateInput()
{
    // 验证工序编号
    QString processId = m_processIdEdit->text().trimmed();
    if (processId.isEmpty()) {
        QMessageBox::warning(this, "验证错误", "请输入工序编号！");
        m_processIdEdit->setFocus();
        return false;
    }
    
    // 验证工序编号唯一性
    if (isProcessIdExists(processId)) {
        QMessageBox::warning(this, "验证错误", "工序编号已存在，请使用其他编号！");
        m_processIdEdit->setFocus();
        return false;
    }
    
    // 验证工序名称
    QString name = m_nameEdit->text().trimmed();
    if (name.isEmpty()) {
        QMessageBox::warning(this, "验证错误", "请输入工序名称！");
        m_nameEdit->setFocus();
        return false;
    }
    
    // 验证计件单价
    if (m_pieceRateSpinBox->value() <= 0) {
        QMessageBox::warning(this, "验证错误", "计件单价必须大于0！");
        m_pieceRateSpinBox->setFocus();
        return false;
    }
    
    // 验证班组选择
    if (m_departmentCombo->currentIndex() < 0) {
        QMessageBox::warning(this, "验证错误", "请选择所属班组！");
        m_departmentCombo->setFocus();
        return false;
    }
    
    return true;
}

void ProcessDialog::accept()
{
    if (validateInput()) {
        QDialog::accept();
    }
}

void ProcessDialog::reject()
{
    QDialog::reject();
}

// Getter方法
QString ProcessDialog::getProcessId() const
{
    return m_processIdEdit->text().trimmed();
}

QString ProcessDialog::getProcessName() const
{
    return m_nameEdit->text().trimmed();
}

QString ProcessDialog::getDescription() const
{
    return m_descriptionEdit->toPlainText().trimmed();
}

double ProcessDialog::getPieceRate() const
{
    return m_pieceRateSpinBox->value();
}

int ProcessDialog::getDepartmentId() const
{
    QString departmentName = m_departmentCombo->currentText();
    return m_departmentMap.value(departmentName, -1);
}

// Setter方法（用于编辑模式）
void ProcessDialog::setProcessInfo(const QString &processId, const QString &name, 
                                  const QString &description, double pieceRate, 
                                  int departmentId)
{
    m_processIdEdit->setText(processId);
    m_nameEdit->setText(name);
    m_descriptionEdit->setPlainText(description);
    m_pieceRateSpinBox->setValue(pieceRate);
    
    // 设置班组选择
    for (auto it = m_departmentMap.begin(); it != m_departmentMap.end(); ++it) {
        if (it.value() == departmentId) {
            m_departmentCombo->setCurrentText(it.key());
            break;
        }
    }
}